<template>
  <el-form
    ref="ElnTemplateSide"
    class="system-user-form"
    :model="formData"
    :rules="formRules"
    :label-position="pageViewMode === 'print' ? 'left' : 'right'"
    status-icon
  >
    <el-row :class="pageViewMode === 'print' ? 'printStyle' : 'none'">
      <el-col :span="span">
        <div v-if="showFieldLabel" class="card-field-label">
          <span>{</span>
          <span>{{ getId("templateCode") }}</span>
          <span>}</span>
        </div>
        <el-form-item
          label="记录编号"
          label-width="80px"
          prop="experimentNumber"
        >
          <el-input
            v-if="pageViewMode !== 'print'"
            v-model="formData.experimentNumber"
            autocomplete="off"
            :disabled="disabled"
          ></el-input>
          <div v-else>{{ formData.experimentNumber }}</div>
        </el-form-item>
      </el-col>

      <el-col :span="span">
        <div v-if="showFieldLabel" class="card-field-label">
          <span>{</span>
          <span>{{ getId("creatorTime") }}</span>
          <span>}</span>
        </div>
        <el-form-item
          v-if="pageViewMode !== 'print'"
          prop="creatorTime"
          label="开展时间"
          :label-width="formLabelWidth"
        >
          <el-date-picker
            v-if="pageViewMode !== 'print'"
            v-model="formData.creatorTime"
            :class="{ readonly: readonly }"
            type="date"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            :disabled="disabled"
          ></el-date-picker>
          <div v-else>{{ prdCreatorTime }}</div>
        </el-form-item>
      </el-col>

      <el-col :span="span">
        <el-form-item
          v-if="pageViewMode === 'print'"
          label="版本编号:A/0"
          prop="creatorName"
          label-width="200px"
          style="margin-left: 100px"
        >
        </el-form-item>
      </el-col>
      <el-col :span="span">
        <div v-if="showFieldLabel" class="card-field-label">
          <span>{</span>
          <span>{{ getId("creatorName") }}</span>
          <span>}</span>
        </div>
        <el-form-item
          v-if="pageViewMode !== 'print'"
          label="检测人"
          prop="creatorName"
          :label-width="formLabelWidth"
        >
          <el-select
            ref="selectDom"
            v-model="formData.creatorName"
            :multiple="true"
            :placeholder="
              pageViewMode !== 'runtime' && operateType === 0
                ? ''
                : '请选择检测人'
            "
            filterable
            remote
            reserve-keyword
            :remote-method="remoteUser"
            :loading="searchUserLoading"
            value-key="id"
            :disabled="disabled"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
          <!-- <div v-else>{{ pdfCreatorName }}</div> -->
        </el-form-item>
      </el-col>
      <el-col v-if="detectionState" :span="span">
        <div v-if="pageViewMode !== 'print'">
          <el-row>
            <el-col :span="12"><span>检测项目结果设置</span></el-col>
          </el-row>
          <el-row>
            <el-table
              ref="tableDetectionItemAll"
              :data="formData.tableDetectionItemAll"
              :header-cell-style="{ textAlign: 'center' }"
              :cell-style="{ textAlign: 'center' }"
              border
              height="350px"
              style="width: 100%"
            >
              <el-table-column
                prop="detectionItemName"
                label="检测项目"
                width="100px"
              />
              <el-table-column label="操作" width="70px">
                <template v-slot="scope">
                  <el-row>
                    <el-col :span="12">
                      <i
                        class="el-icon-aim"
                        :style="scope.row.iconStyle"
                        @click="
                          readonly ? null : orientation(scope.row, scope.$index)
                        "
                      ></i>
                    </el-col>
                    <el-col :span="12">
                      <i
                        class="el-icon-refresh-left"
                        :class="operateClass"
                        style="font-size: 25px; cursor: pointer"
                        @click="
                          readonly
                            ? null
                            : againOrientation(scope.row, scope.$index)
                        "
                      ></i>
                    </el-col>
                  </el-row>
                </template>
              </el-table-column>
              <el-table-column
                prop="dataPositioning"
                label="数据定位"
                width="100px"
              />
            </el-table>
          </el-row>
        </div>
      </el-col>
    </el-row>
  </el-form>
</template>
<script>
import { getUserListNoPage } from "../../../api/Permission/user.js";
import { formatTimeMin } from "../../../utils/time.js";
export default {
  name: "ElnTemplateSide",
  props: {
    detectionState: {
      type: Boolean,
      default: true,
    },
    formData: {
      type: Object,
      default: () => {},
    },
    operateType: {
      type: Number,
      default: 1,
    },
    pageViewMode: {
      type: String,
      default: "",
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    formLabelWidth: {
      type: String,
      default: "80px",
    },
    showFieldLabel: {
      type: Boolean,
      default: false,
    },
    leftData: {
      type: Array,
      default: () => [],
    },
    // 必填状态
    requiredState: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      searchUserLoading: false,
      userList: [],
      detectionItemResultTable: [],
      disabled: false,
      formRules: {
        experimentNumber: { required: true, message: "记录编号不能为空" },
        sampleCategoryName: { required: true, message: "样品类别不能为空" },
        articleNumber: { required: true, message: "品号不能为空" },
        creatorTime: { required: true, message: "开展时间不能为空" },
        creatorName: [{ required: true, message: "检测人不能为空" }],
      },
      locationIndex: 0,
      // 在table组件内cancelCellSelect方法使用
      operateClass: "el-row__table-operate",
      projectList: [],
    };
  },
  computed: {
    span() {
      return this.pageViewMode === "print" ? 12 : 24;
    },
    prdCreatorTime() {
      return formatTimeMin(this.formData.creatorTime);
    },
  },
  created() {
    // zsk-2024/06/12-前端去重,app添加的检测人可能会重复
    try {
      this.formData.creatorName = Array.from(
        new Set(this.formData.creatorName || [])
      );
      this.formData.creatorName = this.formData.creatorName.filter(
        (item) => item !== "0"
      );
    } catch (error) {
      console.log(error);
    }
    this.disabled = this.readonly || this.pageViewMode !== "runtime";
    this.disabled && (this.formRules = null);
    // 不是必填
    if (!this.requiredState) {
      this.formRules = null;
    }
    if (this.formData.tableDetectionItemAll) {
      this.projectList = this.formData.tableDetectionItemAll.map((x) => {
        const obj = {
          projectId: x.id,
          tableId: "",
          tableTitle: "",
          cellData: [],
          trans: "",
          check: false,
        };
        return obj;
      });
    }

    this.remoteUser();
  },
  methods: {
    // 定位
    orientation(row, index) {
      var state = false;
      if (row.iconStyle === "font-size: 25px;color:red;cursor: pointer") {
        state = true;
      }
      for (let i = 0; i < this.formData.tableDetectionItemAll.length; i++) {
        this.formData.tableDetectionItemAll[i].iconStyle =
          "font-size: 25px;cursor: pointer;";
      }
      if (!state) {
        this.locationIndex = -1;
        this.locationIndex = index;
        row.iconStyle = "font-size: 25px;color:red;cursor: pointer";
      }

      const row2 = this.projectList[index];
      this.projectList.forEach((x, i) => {
        x.check = i === index ? !x.check : false;
      });

      this.$emit("setTagConfig", {
        type: state ? "close" : "open",
        projectId: row2.id,
        tableId: row2.tableId,
        cellData: !state ? row2.cellData : [],
        operateClass: this.operateClass,
      });
    },
    // 重新定位
    againOrientation(row, index) {
      this.formData.tableDetectionItemAll[index].dataPositioning = "";
      this.formData.tableDetectionItemAll[index].tableId = "0";
      this.formData.tableDetectionItemAll[index].tableName = "";
      this.formData.tableDetectionItemAll[index].title = "";
      this.formData.tableDetectionItemAll[index].resultColumn = -1;
      this.formData.tableDetectionItemAll[index].resultRow = -1;
      const row2 = this.projectList[index];
      row2.tableId = "";
      row2.cellData = [];
      this.$emit("setTagConfig", {
        type: "reset",
      });
    },
    addRowOrCol(param, type) {
      var data = param.data;

      // 循环表格数据找到和这个加行表对应的数据
      for (let i = 0; i < this.formData.tableDetectionItemAll.length; i++) {
        var tableData = this.formData.tableDetectionItemAll[i];
        if (tableData.tableId === param.id) {
          // 判断加行方向
          if (data.direction === "lefttop") {
            if (type === "row") {
              // 表格中大于等于目标行的都要加
              if (tableData.resultRow >= data.index) {
                this.formData.tableDetectionItemAll[i].resultRow =
                  Number(this.formData.tableDetectionItemAll[i].resultRow) +
                  Number(data.value);
                this.fromDataPositioning(i);
              }
            } else if (type === "col") {
              if (tableData.resultColumn >= data.index) {
                this.formData.tableDetectionItemAll[i].resultColumn =
                  Number(this.formData.tableDetectionItemAll[i].resultColumn) +
                  Number(data.value);
                this.fromDataPositioning(i);
              }
            }
          } else if (data.direction === "rightbottom") {
            if (type === "row") {
              // 表格中大于目标行的都要加
              if (tableData.resultRow > data.index) {
                this.formData.tableDetectionItemAll[i].resultRow =
                  Number(this.formData.tableDetectionItemAll[i].resultRow) +
                  Number(data.value);

                this.fromDataPositioning(i);
              }
            } else if (type === "col") {
              if (tableData.resultColumn > data.index) {
                this.formData.tableDetectionItemAll[i].resultColumn =
                  Number(this.formData.tableDetectionItemAll[i].resultColumn) +
                  Number(data.value);
                this.fromDataPositioning(i);
              }
            }
          }
        }
      }
    },
    fromDataPositioning(index) {
      const column = String.fromCharCode(
        65 + this.formData.tableDetectionItemAll[index].resultColumn
      );
      const row = this.formData.tableDetectionItemAll[index].resultRow + 1;

      this.formData.tableDetectionItemAll[index].dataPositioning =
        this.formData.tableDetectionItemAll[index].tableName +
        ":" +
        column +
        row;
    },
    deleteRowOrCol(param) {
      for (let i = 0; i < this.formData.tableDetectionItemAll.length; i++) {
        var data = this.formData.tableDetectionItemAll[i];

        if (data.tableId === param.id) {
          // 删除列
          if (param.data.col !== -1) {
            if (data.resultColumn === param.data.col) {
              this.againOrientation(null, i);
            } else if (data.resultColumn > param.data.col) {
              // 大于这一列的都减一
              this.formData.tableDetectionItemAll[i].resultColumn =
                Number(this.formData.tableDetectionItemAll[i].resultColumn) - 1;

              // this.formData.tableDetectionItemAll[i].resultColumn =
              //   this.formData.tableDetectionItemAll[i].resultColumn;
              this.fromDataPositioning(i);
            }
            // 删除行
          } else if (param.data.row !== -1) {
            if (data.resultRow === param.data.row) {
              this.againOrientation(null, i);
            } else if (data.resultRow > param.data.row) {
              this.formData.tableDetectionItemAll[i].resultRow =
                Number(this.formData.tableDetectionItemAll[i].resultRow) - 1;

              // this.formData.tableDetectionItemAll[i].resultRow =
              //   this.formData.tableDetectionItemAll[i].resultRow;
              this.fromDataPositioning(i);
            }
          }
        }
      }
    },
    // 接收父元素传来的table页面参数
    tagValue2Select(param) {
      if (
        Object.prototype.toString.call(param.data).slice(8, -1) === "Object"
      ) {
        switch (param.data.type) {
          case "close":
            this.projectList.forEach((x, i) => {
              x.check = false;
            });
            break;
          case "setTitle":
            {
              const idx = this.projectList.findIndex(
                (x) => x.tableId === param.id
              );
              if (idx > -1) {
                this.projectList[idx].tableTitle = param.title;
              }
              // 修改检测项目中table表名称
              if (
                this.formData.tableDetectionItemAll !== undefined &&
                this.formData.tableDetectionItemAll !== null &&
                this.formData.tableDetectionItemAll.length !== 0
              ) {
                const tableindex =
                  this.formData.tableDetectionItemAll.findIndex(
                    (x) => x.tableId === param.id
                  );
                if (tableindex > -1) {
                  var data = this.formData.tableDetectionItemAll[tableindex];
                  this.formData.tableDetectionItemAll[tableindex].tableName =
                    param.title;
                  const column = String.fromCharCode(65 + data.resultColumn); // 将数字转换为Excel中的列字母
                  const row = data.resultRow + 1;
                  this.formData.tableDetectionItemAll[
                    tableindex
                  ].dataPositioning = param.title + ":" + column + row;
                }
              }
            }
            break;
          case "delete":
            this.deleteRowOrCol(param);
            break;
          case "addrow":
            this.addRowOrCol(param, "row");
            break;
          case "addcolumn":
            this.addRowOrCol(param, "col");
            break;
        }
        return;
      } else {
        const column = String.fromCharCode(65 + param.data[0].c); // 将数字转换为Excel中的列字母
        const row = param.data[0].r + 1;

        this.formData.tableDetectionItemAll[
          this.locationIndex
        ].dataPositioning = param.title + ":" + column + row;
        this.formData.tableDetectionItemAll[this.locationIndex].tableId =
          param.id;
        this.formData.tableDetectionItemAll[this.locationIndex].tableName =
          param.title;
        this.formData.tableDetectionItemAll[this.locationIndex].resultColumn =
          param.data[0].c;
        this.formData.tableDetectionItemAll[this.locationIndex].resultRow =
          param.data[0].r;
      }
      const idx = this.projectList.findIndex((x) => x.check);
      if (idx > -1) {
        this.projectList[idx].tableId = param.id;
        this.projectList[idx].tableTitle = param.title;
        this.projectList[idx].cellData = param.data;
        if (!param.data.length) return;
        const { r, c } = param.data[0];
        const code = String.fromCharCode(64 + parseInt(Number(c) + 1));
        this.projectList[idx].trans = `${code}${Number(r) + 1}`;
      }
    },
    getId(code) {
      return this.leftData.find((x) => x.code === code)?.id;
    },
    validate() {
      return new Promise((resolve) => {
        this.$refs.ElnTemplateSide.validate((val) => {
          resolve(val);
        });
      });
    },
    // 搜索人员
    getUser(name = "") {
      return new Promise((resolve) => {
        getUserListNoPage({ name }).then((res) => {
          resolve(res);
        });
      });
    },
    async remoteUser(query) {
      this.searchUserLoading = true;
      const filter = await this.getUser(query);
      if (filter && filter.data && filter.data.length) {
        this.userList = filter.data;
      }
      this.searchUserLoading = false;
    },
  },
};
</script>
<style lang="scss">
.system-user-form {
  .printStyle {
    margin-left: 18px;
  }
  .el-form-item {
    .el-form-item__label {
      height: 16px;
      font-size: 12px;
      font-family: "Microsoft YaHei";
      color: #000;
      line-height: 16px;
      margin-top: 9px;
    }

    .card-field-label {
      display: block;
      width: 100%;
      height: 16px;
      font-size: 0;
      text-align: left;
      margin-bottom: 6px;
      padding-left: 6px;

      span {
        font-family: "Microsoft YaHei";
        color: #da1c76;
        line-height: 16px;
        font-size: 12px;
      }
    }
  }
}
</style>
